package com.wcbtest.dem02.service;

import com.jcraft.jsch.*;
import com.wcbtest.dem02.entity.SshConfig;
import com.wcbtest.dem02.entity.SshResult;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Service
public class TopCommandExecutor {



    public SshResult executeTopCommand() throws JSchException, IOException {
        SshConfig config = new SshConfig();
        config.setHost("192.168.110.130");
        config.setPort(22);
        config.setUsername("root");
        config.setPassword("123456");

        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;

        try {
            // 创建SSH会话
            session = jsch.getSession(config.getUsername(), config.getHost(), config.getPort());
            
            // 设置私钥(如果有)
            if (config.getPrivateKeyPath() != null && !config.getPrivateKeyPath().isEmpty()) {
                if (config.getPrivateKeyPassphrase() != null && !config.getPrivateKeyPassphrase().isEmpty()) {
                    jsch.addIdentity(config.getPrivateKeyPath(), config.getPrivateKeyPassphrase());
                } else {
                    jsch.addIdentity(config.getPrivateKeyPath());
                }
            } else {
                // 设置密码
                session.setPassword(config.getPassword());
            }

            // 禁用严格主机密钥检查
            java.util.Properties configProps = new java.util.Properties();
            configProps.put("StrictHostKeyChecking", "no");
            session.setConfig(configProps);

            // 连接SSH服务器
            session.connect();

            // 打开执行命令的通道
            channel = session.openChannel("exec");
            //((ChannelExec) channel).setCommand("top");
            ((ChannelExec) channel).setCommand("top -b -n 1");

            // 获取命令输出流
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);
            InputStream inputStream = channel.getInputStream();
            InputStream errorStream = ((ChannelExec) channel).getErrStream();
            channel.connect();

            //// 读取命令输出
            //BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            //StringBuilder output = new StringBuilder();
            //String line;
            //while ((line = reader.readLine()) != null) {
            //    output.append(line).append("\n");
            //}

            // 读取标准输出
            String stdout = readStream(inputStream);
            // 读取错误输出
            String stderr = readStream(errorStream);

            // 等待命令执行完成并获取退出状态
            while (channel.isConnected()) {
                Thread.sleep(100);
            }
            int exitStatus = channel.getExitStatus();

            return new SshResult(exitStatus,stdout,stderr);
        }catch (Exception e){
            return null;
        }finally {
            // 关闭通道和会话
            if (channel != null) channel.disconnect();
            if (session != null) session.disconnect();
        }
    }
    /**
     * 读取输入流内容
     */
    private static String readStream(InputStream inputStream) throws java.io.IOException {
        StringBuilder result = new StringBuilder();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8)
        );

        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line).append("\n");
        }

        return result.toString();
    }



}

